package com.revai.engine.basic.controller;

import com.revai.engine.common.api.CommonResult;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by CodeGenerator on 2024/01/11.w
 */
@Api(tags = "BasicController", description = "数据IO操作接口")
@Controller
@RequestMapping("${server.api-path}/inputUploader")
public class DataIOController {

    @Value("${spring.engine.upload.path}")
    private String UPLOAD_PATH;

    @ApiOperation(value = "文件上传")
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult<Map<String, ?>> handleFileUpload(MultipartFile file) throws IOException {
        // 获取文件名
        String fileName = file.getOriginalFilename();
        String fileDir = "/upload/";
        // 设置文件保存路径
        Path filePath = Paths.get(UPLOAD_PATH, fileDir, fileName);
        Path savePath = Paths.get(UPLOAD_PATH, fileDir);
        File saveFile = savePath.toFile();
        if (!saveFile.exists()) {
            saveFile.mkdirs();
        }
        // 将文件保存到指定路径
        Files.copy(file.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);
        Map<String, String> res = new HashMap<>();
        res.put("file", "/data/" + (fileDir.replaceAll("^/|/$", "")) + "/" + fileName);
        return CommonResult.success(res);
    }
}
